<template>
  <view class="index-page">
    <!-- 搜索框 -->
    <view class="search-box">
      <up-search
          placeholder="搜索商品"
          shape="round"
          bg-color="#f8f8f8"
          border-color="#eee"
          @search="handleSearch"
      ></up-search>
    </view>

    <!-- 顶部菜单 -->
    <view class="top-menu">
      <view class="menu-item" @click="navigateTo('orders')">
        <i class="fa fa-list-alt"></i>
        <text>我的订单</text>
      </view>
      <view class="menu-item" @click="navigateTo('coupon')">
        <i class="fa fa-shopping-coupon"></i>
        <text>卡卷包</text>
      </view>
      <view class="menu-item" @click="navigateTo('cards')">
        <i class="fa fa-ticket"></i>
        <text>我的关注</text>
      </view>
      <view class="menu-item" @click="navigateTo('comment')">
        <i class="fa fa-heart"></i>
        <text>我的评价</text>
      </view>
    </view>

    <!-- 分类浏览 -->
    <view class="category-section">
      <view class="section-header">
        <text class="section-title">分类浏览</text>
      </view>
      <view class="category-grid">
        <!-- 点击分类时传入当前分类的typeId -->
        <view class="category-item" v-for="(category, index) in categories" :key="index" @click="loadGoodsList(category.typeId)">
          <view class="category-icon" :style="{ backgroundColor: category.bgColor }">
            <image :src="category.icon" class="icon-image"></image>
          </view>
          <text class="category-name">{{ category.name }}</text>
        </view>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-section">
      <view class="section-header">
        <!-- 显示当前分类名称，默认显示"热门闲置" -->
        <text class="section-title">{{ currentCategoryName }}</text>
        <button class="more-btn" @click="navigateToMore">全部</button>
      </view>
      <view class="goods-grid">
        <view
            class="goods-card"
            v-for="(item, index) in goodsList"
            :key="index"
            @click="goToGoodsDetail(item)"
        >
          <view class="card-header">
            <image
                :src="item.avatar || '/static/default-avatar.png'"
                mode="aspectFill"
                class="seller-avatar"
            ></image>
            <text class="seller-name">{{ item.nickName || '匿名用户' }}</text>
            <text class="status-tag" :style="{ backgroundColor: getStatusColor(item.status) }">{{ item.status || '出售中' }}</text>
          </view>
          <image
              :src="item.images[0] || '/static/default-image.png'"
              mode="aspectFill"
              class="goods-image"
          ></image>
          <view class="card-body">
            <text class="goods-title">{{ item.title }}</text>
            <text class="goods-desc">{{ item.description }}</text>
            <view class="price-info">
              <text class="price">¥{{ item.price }}</text>
            </view>
          </view>
        </view>

        <!-- 空状态显示 -->
        <view v-if="goodsList.length === 0 && !isLoading" class="empty-state">
          <up-icon name="goods" size="60" color="#ccc"></up-icon>
          <text class="empty-text">暂无该分类商品</text>
        </view>

        <!-- 加载中状态 -->
        <view v-if="isLoading" class="loading-state">
          <text class="loading-text">加载中...</text>
        </view>
      </view>
    </view>
  </view>
  <my-custom-tab-bar />
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import { selectList } from "@/apis/shopAPI";
import MyCustomTabBar from "@/components/custom-tab-bar/my-custom-tab-bar.vue";

// 商品列表数据
const goodsList = ref([]);
// 加载状态
const isLoading = ref(false);
// 当前选中的分类ID
const currentTypeId = ref(null);
// 当前分类名称
const currentCategoryName = ref('');

// 分类数据
const categories = ref([
  { name: "电子数码", icon: "/static/icon/shop/shop-digital.png", bgColor: "#f9f0ff", typeId: 1 },
  { name: "书籍教材", icon: "/static/icon/shop/shop-book.png", bgColor: "#f9f0ff", typeId: 2 },
  { name: "运动户外", icon: "/static/icon/shop/shop-sport.png", bgColor: "#f0fff4", typeId: 3 },
  { name: "家居日用", icon: "/static/icon/shop/shop-daily.png", bgColor: "#fff7e6", typeId: 4 },
  { name: "游戏娱乐", icon: "/static/icon/shop/shop-game.png", bgColor: "#fff1f0", typeId: 5 },
  { name: "服装配饰", icon: "/static/icon/shop/shop-cloth.png", bgColor: "#e6f4ff", typeId: 6 },
  { name: "礼品礼物", icon: "/static/icon/shop/shop-gift.png", bgColor: "#fff0f6", typeId: 7 },
  { name: "更多分类", icon: "/static/icon/shop/shop-more.png", bgColor: "#f5f5f5", typeId: 8 }
]);

// 页面加载时加载全部商品
onMounted(() => {
  loadGoodsList();
});
const handleSearch = () => {
  loadGoodsList();
}
// 加载商品列表（支持传入分类ID）
const loadGoodsList = async (typeId) => {
  // 更新当前分类状态
  currentTypeId.value = typeId;

  // 获取当前分类名称
  if (typeId) {
    const currentCategory = categories.value.find(cat => cat.typeId === typeId);
    currentCategoryName.value = currentCategory ? currentCategory.name : '分类商品';
  } else {
    currentCategoryName.value = '热门闲置'; // 默认分类名称
  }

  // 显示加载状态
  isLoading.value = true;
  goodsList.value = []; // 清空现有列表

  try {
    // 构造查询参数，传入分类ID（如果有）
    const queryParams = typeId ? { typeId } : {};

    // 调用接口查询商品
    const response = await selectList(queryParams);

    if (response.data.code === 200) {
      goodsList.value = response.data.data.list.map(item => ({
        id: item.id,
        avatar: item.avatar,
        nickName: item.nickName,
        title: item.title,
        description: item.description,
        images: item.file && item.file
            ? JSON.parse(item.file)
            : ['/static/default-image.png'],
        price: item.price,
        status: item.status || '出售中',
        typeId: item.typeId,
        userId: item.userId,
        createTime: item.createTime ? new Date(item.createTime).toLocaleDateString() : '未知时间'
      }));
    } else {
      console.error('获取商品数据失败:', response.message);
      uni.showToast({ title: '获取商品失败', icon: 'none' });
    }
  } catch (error) {
    console.error('请求商品数据异常:', error);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  } finally {
    // 关闭加载状态
    isLoading.value = false;
  }
};

// 根据状态获取颜色
const getStatusColor = (status) => {
  switch (status) {
    case '已售出':
      return '#f5222d';
    case '已下架':
      return '#bfbfbf';
    default:
      return '#52c41a';
  }
};

// 跳转到商品详情页
const goToGoodsDetail = (item) => {
  console.log('跳转到商品详情:', item);
  uni.navigateTo({
    url: `/pages/shop/shop-detail?itemId=${item.id || 'mock'}_${Date.now()}`,
    success: function(res) {
      res.eventChannel.emit('acceptDataFromOpenerPage', {
        itemId: item.id,
        itemData: item
      });
    },
    fail: function(err) {
      console.error('跳转失败:', err);
      uni.showToast({ title: '跳转失败，请重试', icon: 'none' });
    }
  });
};

// 导航到不同页面
const navigateTo = (page) => {
  switch (page) {
    case 'orders':
      uni.navigateTo({ url: '/pages/myOrder/myOrder' });
      break;
    case 'coupon':
      uni.navigateTo({ url: '/pages/shop/my-coupon' });
      break;
    case 'cards':
      uni.navigateTo({ url: '/pages/cards/cards' });
      break;
    case 'follows':
      uni.navigateTo({ url: '/pages/follows/follows' });
      break;
  }
};

// 跳转到更多商品页
const navigateToMore = (typeId => {
  try {
    // 构造查询参数，传入分类ID（如果有）
    const queryParams = typeId ? { typeId } : {};
    // 调用接口查询商品
    const response =  selectList(queryParams);

    if (response.data.code === 200) {
      goodsList.value = response.data.data.list.map(item => ({
        id: item.id,
        avatar: item.avatar,
        nickName: item.nickName,
        title: item.title,
        description: item.description,
        images: item.file && item.file
            ? JSON.parse(item.file)
            : ['/static/default-image.png'],
        price: item.price,
        status: item.status || '出售中',
        typeId: item.typeId,
        userId: item.userId,
        createTime: item.createTime ? new Date(item.createTime).toLocaleDateString() : '未知时间'
      }));
    } else {
      console.error('获取商品数据失败:', response.message);
      uni.showToast({ title: '获取商品失败', icon: 'none' });
    }
  } catch (error) {
    console.error('请求商品数据异常:', error);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  } finally {
    // 关闭加载状态
    isLoading.value = false;
  }
});
</script>

<style scoped>
.index-page {
  padding: 16px;
  background-color: #f8f8f8;
}
.index-page {
  padding: 16px;
  background-color: #f8f8f8;
}

/* 搜索框 */
.search-box {
  margin-bottom: 16px;
}
.icon-image {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
}
/* 顶部菜单 */
.top-menu {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 12px 0;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.menu-item i {
  font-size: 20px;
  color: #ff4d4f;
  margin-bottom: 4px;
}

.menu-item text {
  font-size: 12px;
  color: #333;
}

/* 分类浏览 */
.category-section {
  margin-bottom: 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.more-btn {
  font-size: 12px;
  color: #ff4d4f;
  margin-left: 450rpx;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.category-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6px;
}

.category-icon i {
  font-size: 18px;
}

.category-name {
  font-size: 12px;
  color: #333;
}

/* 商品列表 */
.goods-section {
  margin-bottom: 20px;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.goods-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;
}

.goods-card:active {
  transform: scale(0.98);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 8px;
}

.seller-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 6px;
}

.seller-name {
  font-size: 12px;
  color: #666;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-tag {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 4px;
  color: #fff;
}

.goods-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.card-body {
  padding: 8px;
}

.goods-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 4px;
}

.goods-desc {
  font-size: 12px;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 6px;
}

.price-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.price {
  font-size: 14px;
  font-weight: 500;
  color: #ff4d4f;
}

/* 空状态 */
.empty-state {
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #999;
}

.empty-text {
  margin-top: 12px;
  font-size: 14px;
}
/* 加载中状态 */
.loading-state {
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #999;
}

.loading-text {
  margin-top: 12px;
  font-size: 14px;
}
</style>
